package top.hcode.hoj.service.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nutz.lang.Strings;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import top.hcode.hoj.dao.TyOrgDao;
import top.hcode.hoj.pojo.dto.QuerySampleDTO;
import top.hcode.hoj.pojo.dto.TyOrgSyncDTO;
import top.hcode.hoj.pojo.entity.org.TyOrg;


/**
 * @author orangej
 * @since 2025-01-22
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AdminTyOrgService {
    private final TyOrgDao tyOrgDao;
    private final TyOrgSyncService tyOrgSyncService;

    public IPage<TyOrg> getTyOrgList(QuerySampleDTO querySampleDTO) {
        IPage<TyOrg> pager = new Page<>(querySampleDTO.getCurrentPage(), querySampleDTO.getLimit());

        QueryWrapper<TyOrg> query = new QueryWrapper<>();
        if (Strings.isNotBlank(querySampleDTO.getKeyword())) {
            query.like("title", querySampleDTO.getKeyword());
        }
        tyOrgDao.page(pager, query);
        return pager;
    }

    public TyOrg getTyOrg(Long id) {
        return tyOrgDao.getById(id);
    }

    public TyOrg saveTyOrg(TyOrg tyOrg) {
        tyOrgDao.saveOrUpdate(tyOrg);
        return tyOrg;
    }

    public void deleteTyOrg(Long id) {
        tyOrgDao.removeById(id);
    }

    @Async
    public void asyncSyncAndExport(TyOrgSyncDTO syncDTO) {
        try {
            log.info("开始异步执行天喻数据同步和导出任务");
            tyOrgSyncService.syncAndExport(syncDTO);
            log.info("天喻数据同步和导出任务完成");
        } catch (Exception e) {
            log.error("天喻数据同步和导出失败", e);
        }
    }
    
    public boolean isSyncInProgress() {
        return tyOrgSyncService.isSyncInProgress();
    }
}
